package com.webserver.core;

import com.webserver.servlet.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServerContext {
    private static Map<String, HttpServlet> hashMap=new HashMap<>();
    static {
        initServletMap();
    }
    //业务继承超类后放入hashMap,即可以调用对象又可以实现service()方法
    private static void initServletMap(){
//        hashMap.put("/myweb/register",new register());
//        hashMap.put("/myweb/loginUser",new Login());
//        hashMap.put("/myweb/change_password",new Change_Password());
//        hashMap.put("/myweb/ShowAllUserServlet",new ShowAllUser());
//        hashMap.put("/myweb/ToUpdateServlet",new ToUpdateServlet());
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read("./Webapps/servlets.xml");
            Element root = doc.getRootElement();
            List<Element> list = root.elements("servlet");
            for(Element e : list){
                String key = e.attributeValue("path");
                String className = e.attributeValue("className");
                Class cls = Class.forName(className);
                HttpServlet servlet = (HttpServlet) cls.newInstance();
                hashMap.put(key,servlet);
            }
            System.out.println(hashMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static HttpServlet getServlet(String path){
        return hashMap.get(path);
    }

}
